package com.codi.bus.core.service.organ.impl;

import com.codi.base.util.CollectionsUtils;
import com.codi.base.util.EqualsUtil;
import com.codi.base.util.ExceptionUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.FundBusinCodeUtil;
import com.codi.bus.constant.FundConst;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.dao.LookupDao;
import com.codi.bus.core.domain.Lookup;
import com.codi.bus.core.domain.OrganBank;
import com.codi.bus.core.domain.OrganProfile;
import com.codi.bus.core.resultModel.*;
import com.codi.bus.core.service.ApplyRecordService;
import com.codi.bus.core.service.FundDetailService;
import com.codi.bus.core.service.model.*;
import com.codi.bus.core.service.organ.OrganApplyRecordService;
import com.codi.bus.core.service.organ.OrganBankService;
import com.codi.bus.core.service.organ.OrganProfileService;
import com.codi.bus.core.service.util.CalculateAssetsUtils;
import com.codi.bus.core.service.util.HundsunUtils;
import com.codi.bus.core.service.util.ModelPopulateUtils;
import com.codi.bus.exception.BaseException;
import com.codi.bus.exception.SystemDBException;
import com.codi.fundData.domain.FundDetail;
import com.codi.message.constant.ErrorConstant;
import com.codi.message.util.MessageUtil;
import com.codi.trade.dto.HsDividendQryDto;
import com.codi.trade.service.DividendsQueryService;
import com.codi.trade.service.TradeApplyQueryService;
import com.codi.trade.service.TradeConfirmQueryService;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author lvgo
 * @version 4.5.0
 * @Description: // 交易记录
 * @date 2018/4/9 11:05
 */
@Service
@Slf4j
public class OrganApplyRecordServiceImpl implements OrganApplyRecordService {

    @Autowired
    private DividendsQueryService dividendsQueryService;

    @Resource(name = "tradeApplyQueryService")
    private TradeApplyQueryService tradeApplyQueryService;

    @Resource(name = "lookupDao")
    private LookupDao lookupDao;

    @Resource(name = "tradeConfirmQueryService")
    private TradeConfirmQueryService tradeConfirmQueryService;

    @Resource(name = "fundDetailService")
    private FundDetailService fundDetailService;

    @Resource
    private ApplyRecordService applyRecordService;

    @Resource
    private OrganBankService organBankService;
    @Resource
    private OrganProfileService organProfileService;


    /**
     * 资产--基金的交易记录
     *
     * @param normalCode 组合代码 非必
     * @param queryType  业务类型, all 全部 onWay 进行中
     * @param userId     用户id
     * @param beginNum
     * @param requestNum
     * @param business
     * @return
     */
    @Override
    public NTradingRecordListResult queryFundRecord(String profileId, String normalCode, String queryType, Long userId, Integer beginNum, Integer requestNum, String business, String allotNo, Boolean isOrganBao) {
        log.info("queryApplys - userId=" + userId);
        OrganProfile organProfile = organProfileService.getById(Long.valueOf(profileId));
        NTradingRecordListResult ntResult = new NTradingRecordListResult();
        ApplyListResult result = new ApplyListResult();
        try {
            // 获取用户
            // 判断是否已开户
            if (organProfile == null || StringUtil.isEmpty(organProfile.getExternalClientId())) {
                ntResult.setSuccess(false);
                ntResult.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
                ntResult.setErrorCode(ErrorConstant.ERROR_NO_ACCOUNT);
                return ntResult;
            }


            //这里应该只需要查询非组合基金的交易记录  目前非组合基金的交易记录应该需要通过传tradeAccount来区分
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            if (StringUtils.isNotBlank(allotNo)) {
                map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
                    organProfile.getExternalClientId(), "", "", allotNo, "", "", "", "", "", "", "", "", "");
            } else {
                map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
                    organProfile.getExternalClientId(), "", "", "", "", "", "", "", "", "", "", "", "");
            }
            // 查询结果
            HundsunUtils.ConvertToList(map, list, ntResult);
            if (!ntResult.getSuccess()) {
                ntResult.setSuccess(false);
                ntResult.setErrorType(GlobalConstant.ERROR_TYPE_SYSTEM);
                ntResult.setErrorCode(ErrorConstant.ERROR_HUNDSUNAPI_WRONG);
                ntResult.setErrorMessage(result.getErrorMessage());
                return ntResult;
            }
            // 交易业务名称
            List<Lookup> tradeLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_BUSINAME);
            // 银行名称
            List<Lookup> bankLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);
            // populate
            List<ApplyModel> fundApplys = ModelPopulateUtils.populateApply2(list, result, tradeLookups, bankLookups, true);

            //过滤组合基金
            List<ApplyModel> applys = new ArrayList<>();
            for (ApplyModel applyModel : fundApplys) {
                //赎回转购的业务辅助标识
                if (GlobalConstant.BUSIN_ASS_CODE_CURRENCY_SEEL_THEN_BUY.equals(applyModel.getBusinAssCode())) {
                    if (!Strings.isNullOrEmpty(applyModel.getOriginalAppno())) {
                        for (ApplyModel apply : fundApplys) {
                            if (applyModel.getOriginalAppno().equals(apply.getAllotNo())) {
                                applyModel.setBusinAssName(apply.getFundCode());
                            }
                        }
                    }
                }
                //过滤组合 记录
                if (Strings.isNullOrEmpty(applyModel.getPortfolioCode())) {
                    applys.add(applyModel);
                }
            }
            // 通过 isOrganBao 字段 过滤相应的基金
            normalFilterOrganBao(applys, isOrganBao);

            // 从聚源获取基金信息
            List<String> fundCodeList = new ArrayList<String>();
            for (ApplyModel shareModel : applys) {
                if (!Strings.isNullOrEmpty(shareModel.getBusinAssName()) && !fundCodeList.contains(shareModel.getBusinAssName())) {
                    fundCodeList.add(shareModel.getBusinAssName());
                }
                if (!fundCodeList.contains(shareModel.getFundCode())) {
                    fundCodeList.add(shareModel.getFundCode());
                }
                shareModel.setIsOrg(true);
            }

            List<FundNetValueResult> fundNetValueList = null;
            try {
                fundNetValueList = fundDetailService.getFundNetValueByBatch(fundCodeList, new Date());

            } catch (Exception ex) {
                ExceptionUtil.logError(log, "queryApplys - fundDetailService - Exception:", ex);
                ntResult.setSuccess(false);
                ntResult.setErrorType(GlobalConstant.ERROR_TYPE_SYSTEM);
                ntResult.setErrorCode(ErrorConstant.ERROR_GILDATA_WRONG);
                return ntResult;
            }

            // 如果没有找到聚源数据，则默认为空数组
            if (fundNetValueList == null) {
                fundNetValueList = new ArrayList<>();
            }

            for (ApplyModel model : applys) {
                // 设置基金信息
                for (FundNetValueResult fundNetValue : fundNetValueList) {
                    if (fundNetValue == null) {
                        continue;
                    }
                    if (fundNetValue.getFundCode().equals(model.getFundCode())) {
                        model.setFundName(fundNetValue.getChiNameAbbr());
                    }
                    if (fundNetValue.getFundCode().equals(model.getBusinAssName())) {
                        model.setBusinAssName("瑞富宝-" + fundNetValue.getChiNameAbbr());
                    }
                }
            }


            // business 业务类型
            business = applyRecordService.businessCode(business);


            // 正在进行中的交易
            List<ApplyModel> intradingApplys;
            // 指定组合的交易记录
            List<ApplyModel> theCodeApplys;
            // 根据业务参数 查询交易记录
            List<ApplyModel> filtrateNormalApplys;

            // 1.进行中的交易记录
            if (StringUtils.isNotBlank(queryType) && GlobalConstant.APPLY_RECORD_ONWAY.equals(queryType)) {
                intradingApplys = applyRecordService.getNormalIntradingApplys(applys);
                applys.clear();
                applys.addAll(intradingApplys);
            }

            // 2.指定基金交易记录
            if (StringUtils.isNotBlank(normalCode)) {
                theCodeApplys = applyRecordService.getNormalCodeApplys(applys, normalCode);
                applys.clear();
                applys.addAll(theCodeApplys);
            }

            // 3.指定业务交易记录
            if (StringUtils.isNotBlank(business) && !GlobalConstant.FUND_BUSIN_CODE_APPLY_BOUNS.equals(business)) {
                filtrateNormalApplys = applyRecordService.normalBusniessData(applys, business);
                applys.clear();
                applys.addAll(filtrateNormalApplys);
            }


            // 分红交易记录
            List<DividendModel> dividendModels = new ArrayList<>();
            boolean isAll = GlobalConstant.APPLY_RECORD_ALL.equals(queryType) && StringUtils.isBlank(business);
            boolean isBouns = GlobalConstant.APPLY_RECORD_ALL.equals(queryType) && (StringUtils.isNotBlank(business) && GlobalConstant.FUND_BUSIN_CODE_APPLY_BOUNS.equals(business));
            if (isAll || isBouns) {
                if (StringUtils.isNotBlank(allotNo)) {
                    dividendModels = getNormalDividendApplys(normalCode, organProfile, allotNo,isOrganBao);
                } else {
                    dividendModels = getNormalDividendApplys(normalCode, organProfile, null,isOrganBao);
                }
            }

            // 过滤机构交易记录
            List<OrganBank> organBanks = organBankService.getListByProfileId(profileId);
            if (organBanks != null && !organBanks.isEmpty()) {
                List<ApplyModel> organApplys = filterOrganApplys(organBanks, applys);
                applys.clear();
                applys.addAll(organApplys);
            }

            // 组装基金交易记录模型数据
            List<NTradingRecord> nTradingRecords = new ArrayList<>();
            List<NTradingRecord> nTradingRecordReal = new ArrayList<>();
            // 添加基金交易记录
            if (!GlobalConstant.FUND_BUSIN_CODE_APPLY_BOUNS.equals(business)) {
                applys.forEach(apply -> nTradingRecords.add(
                    NTradingRecord.builder()
                        .applyModel(apply)
                        .sortDate(apply.getAllotNo())
                        .state(0).build()
                ));
            }
            // 添加基金分红交易记录
            if (dividendModels != null) {
                dividendModels.forEach(dividendModel -> nTradingRecords.add(
                    NTradingRecord.builder()
                        .dividendModel(dividendModel)
                        .sortDate(dividendModel.getDividendDate() + "000000")
                        .state(1).build()
                ));
            }

            applyRecordService.filtrateFunds(ntResult, nTradingRecords, nTradingRecordReal, beginNum, requestNum);
            ntResult.setNTradingRecords(nTradingRecordReal);
            return ntResult;
        } catch (BaseException baseException) {
            throw baseException;
        } catch (Exception exception) {
            ExceptionUtil.logError(log, "queryApplys - Exception:", exception);
            throw new SystemDBException("queryApplys Failure!", exception);
        }
    }

    private List<ApplyModel> filterOrganApplys(List<OrganBank> organBanks, List<ApplyModel> applys) {
        ArrayList<ApplyModel> applyModels = new ArrayList<>();
        organBanks.forEach(organBank -> applys.forEach(applyModel -> {
            if (organBank.getExternalTradeAccount().equals(applyModel.getTradeAcco())) {
                applyModels.add(applyModel);
            }
        }));
        return applyModels;
    }

    /**
     * 资产--瑞富宝的交易记录
     *
     * @param fundCode   组合代码 非必
     * @param queryType  业务类型, all 全部 onWay 进行中
     * @param userId     用户id
     * @param beginNum
     * @param requestNum
     * @param business
     * @return
     */
    @Override
    public WTradingRecordListResult queryRuifubaoRecord(String profileId, String fundCode, String queryType, Long userId, Integer beginNum, Integer requestNum, String business, String allotNo) {
        // 获取用户
        OrganProfile organProfile = organProfileService.getById(Long.valueOf(profileId));
        WTradingRecordListResult wtResult = new WTradingRecordListResult();
        ApplyListResult result = new ApplyListResult();
        // 判断是否已开户
        if (organProfile == null || StringUtil.isEmpty(organProfile.getExternalClientId())) {
            wtResult.setSuccess(false);
            wtResult.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
            wtResult.setErrorCode(ErrorConstant.ERROR_NO_ACCOUNT);
            wtResult.setErrorMessage(MessageUtil.getErrorMsg(wtResult.getErrorCode()));
            return wtResult;
        }
        // 查出这个用户下所有的交易记录，包括已确认和未确认的，传ClientId
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(allotNo)) {
            map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
                organProfile.getExternalClientId(), "", "", allotNo, "", "", "", "", "", "", "", "", "");
        } else {
            map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
                organProfile.getExternalClientId(), "", "", "", "", "", "", "", "", "", "", "", "");
        }        // 检查查询结果是否OK
        List<Map<String, Object>> list = new ArrayList<>();
        HundsunUtils.ConvertToList(map, list, result);
        if (!result.getSuccess()) {
            wtResult.setSuccess(false);
            wtResult.setErrorType(GlobalConstant.ERROR_TYPE_SYSTEM);
            wtResult.setErrorCode(ErrorConstant.ERROR_HUNDSUNAPI_WRONG);
            wtResult.setErrorMessage(result.getErrorMessage());
            return wtResult;
        }
        // 银行名称
        List<Lookup> bankLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);
        //如果传了T0基金代码
        Set<String> temp = new HashSet<String>();
        temp.add(fundCode);
        final Set<String> t0fundCodeSet = StringUtils.isNotBlank(fundCode) ? temp : CollectionsUtils.newSet(
            lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_T0FUND), new Function<Lookup, String>() {
                @Override
                public String apply(Lookup input) {
                    return input.getRuleValue();
                }
            });

        List<Lookup> businLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_BUSINAME);
        // populate
        List<ApplyModel> applys = ModelPopulateUtils.populateApply(list, result, businLookups, bankLookups);
        // 过滤非T0基金, 并修改T0基金fundBusinCode 为T0申购代码
        org.apache.commons.collections.CollectionUtils.filter(applys, new Predicate() {

            @Override
            public boolean evaluate(Object object) {
                ApplyModel am = (ApplyModel) object;
                am.setIsOrg(true);
                String fundCode = am.getFundCode();
                if (!t0fundCodeSet.contains(fundCode)) {
                    return false;
                }
                String businCode = am.getFundBusinCode();
                if (FundBusinCodeUtil.isBuy(businCode) || FundBusinCodeUtil.isSell(businCode) || FundBusinCodeUtil.isFixBuy(businCode)) {
                    return true;
                }
                return false;
            }
        });

        List<FundNetValueResult> fundNetValueList = fundDetailService
            .getFundNetValueByBatch(Lists.newArrayList(t0fundCodeSet), new Date());
        // 如果没有找到聚源数据，则默认为空数组
        if (fundNetValueList == null) {
            fundNetValueList = new ArrayList<>();
        }

        for (ApplyModel model : applys) {
            if (GlobalConstant.BUSIN_ASS_CODE_CURRENCY_SEEL_THEN_BUY.equals(model.getBusinAssCode())) {
                model.setBusinAssName(GlobalConstant.BUSIN_ASS_NAME_CURRENCY_SEEL_THEN_BUY);

            }
            // 渲染模式为T0基金
            model.setFundType(ApplyModel.FundApplyType.T0);
            // 设置基金信息
            for (FundNetValueResult fundNetValue : fundNetValueList) {
                if (fundNetValue == null) {
                    continue;
                }
                if (fundNetValue.getFundCode().equals(model.getFundCode())) {
                    model.setFundName(fundNetValue.getChiNameAbbr());
                    break;
                }
            }
        }


        // business 业务类型
        business = applyRecordService.businessCode(business);


        // 正在进行中的交易
        List<ApplyModel> intradingApplys;
        // 指定瑞富宝的交易记录
        List<ApplyModel> theCodeApplys;
        // 根据业务参数 查询交易记录
        List<ApplyModel> filtrateWalletApplys;

        // 1.进行中的交易记录
        if (StringUtils.isNotBlank(queryType) && GlobalConstant.APPLY_RECORD_ONWAY.equals(queryType)) {
            intradingApplys = applyRecordService.getNormalIntradingApplys(applys);
            applys.clear();
            applys.addAll(intradingApplys);
        }

        // 2.指定瑞富宝交易记录
        if (StringUtils.isNotBlank(fundCode)) {
            theCodeApplys = applyRecordService.getNormalCodeApplys(applys, fundCode);
            applys.clear();
            applys.addAll(theCodeApplys);
        }

        // 3.指定业务交易记录
        if (StringUtils.isNotBlank(business) && !GlobalConstant.FUND_BUSIN_CODE_APPLY_BOUNS.equals(business)) {
            filtrateWalletApplys = applyRecordService.normalBusniessData(applys, business);
            applys.clear();
            applys.addAll(filtrateWalletApplys);
        }


        // 瑞富宝分红交易记录
        List<DividendModel> dividendModels = new ArrayList<>();
        boolean isAll = GlobalConstant.APPLY_RECORD_ALL.equals(queryType) && StringUtils.isBlank(business);
        boolean isBouns = GlobalConstant.APPLY_RECORD_ALL.equals(queryType) && (StringUtils.isNotBlank(business) && GlobalConstant.FUND_BUSIN_CODE_APPLY_BOUNS.equals(business));
        if (isAll || isBouns) {
            if (StringUtils.isNotBlank(allotNo)) {
                dividendModels = getWalletDividendApplys(organProfile, allotNo);
            } else {
                dividendModels = getWalletDividendApplys(organProfile, null);
            }
        }

        // 过滤机构交易记录
        List<OrganBank> organBanks = organBankService.getListByProfileId(profileId);
        if (organBanks != null && !organBanks.isEmpty()) {
            List<ApplyModel> organApplys = filterOrganApplys(organBanks, applys);
            applys.clear();
            applys.addAll(organApplys);
        }

        // 组装瑞富宝交易记录模型数据
        List<WTradingRecord> wTradingRecords = new ArrayList<>();
        List<WTradingRecord> wTradingRecordReal = new ArrayList<>();
        // 添加瑞富宝交易记录
        if (!GlobalConstant.FUND_BUSIN_CODE_APPLY_BOUNS.equals(business)) {
            applys.forEach(apply -> wTradingRecords.add(
                WTradingRecord.builder()
                    .applyModel(apply)
                    .sortDate(apply.getAllotNo())
                    .state(0).build()
            ));
        }
        // 添加瑞富宝分红交易记录
        if (dividendModels != null) {
            dividendModels.forEach(dividendModel -> wTradingRecords.add(
                WTradingRecord.builder()
                    .dividendModel(dividendModel)
                    .sortDate(dividendModel.getDividendDate() + "000000")
                    .state(1).build()
            ));
        }

        applyRecordService.filtrateWallet(wtResult, wTradingRecords, wTradingRecordReal, beginNum, requestNum);
        wtResult.setSuccess(true);
        wtResult.setWTradingRecords(wTradingRecordReal);
        return wtResult;
    }

    /**
     * 基金详情
     *
     * @param allotNo
     */
    @Override
    public BaseResult queryFundDetail(String profileId, String allotNo) {
        OrganProfile organProfile = organProfileService.getById(Long.valueOf(profileId));
        ConfirmResultModel confirmResultModel = new ConfirmResultModel();
        //交易确认  用于计算累计收益
        Map<String, Object> map = tradeConfirmQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "", organProfile.getExternalClientId(), "", "", allotNo, "", "", "", "", "", "", "", "", "", "", "");

        // 查询结果
        List<Map<String, Object>> list = new ArrayList<>();
        HundsunUtils.ConvertToList(map, list, confirmResultModel);
        if (!confirmResultModel.getSuccess()) {
            return confirmResultModel;
        }

        // populate
        List<ConfirmModel> confirms = ModelPopulateUtils.populateConfirm(list);
        if (confirms.isEmpty()) {
            confirmResultModel.setState(0);
            return confirmResultModel;
        } else {
            ConfirmModel confirmModel = confirms.get(0);
            // 判断基金类型
            FundDetail fundDetail = fundDetailService.getFundDetail(confirmModel.getFundCode());
            String fundType = fundDetail.getFundType();
            Integer fundTypeCode = fundDetail.getFundTypeCode();
            boolean isCurrency = fundTypeCode.equals(FundConst.FUND_TYPE_CODE_CURRENCY);
            confirmResultModel.setFundType(fundType);
            // 申购  定投
            if (GlobalConstant.FUND_BUSIN_CODE_CONFIRM_BUY.equals(confirmModel.getFundBusinCode()) || GlobalConstant.FUND_BUSIN_CODE_CONFIRM_FIX_BUY.equals(confirmModel.getFundBusinCode())) {
                confirmResultModel.setTitle(GlobalConstant.BUY_TRADE_CONFIRM_TITLE);
                confirmResultModel.setExpenseTitle(GlobalConstant.BUY_TRADE_CONFIRM_EXPENSE_TITLE);
                confirmResultModel.setAffirmShareTtile(GlobalConstant.BUY_TRADE_CONFIRM_AFFIRMSHARE_TITLE);
                confirmResultModel.setExpense(confirmModel.getFareSx());
                confirmResultModel.setAffirmShare(confirmModel.getConfirmShares());
                confirmResultModel.setFundBusinCode(confirmModel.getFundBusinCode());
                confirmResultModel.setState(1);
                return confirmResultModel;
            }
            // 赎回
            if (GlobalConstant.FUND_BUSIN_CODE_CONFIRM_SELL.equals(confirmModel.getFundBusinCode()) ||
                GlobalConstant.FUND_BUSIN_CODF_CONFIRM_QUICK_SELL.equals(confirmModel.getFundBusinCode())) {
                confirmResultModel.setTitle(GlobalConstant.SELL_TRADE_CONFIRM_TITLE);
                confirmResultModel.setExpenseTitle(GlobalConstant.SELL_TRADE_CONFIRM_EXPENSE_TITLE);
                confirmResultModel.setAffirmShareTtile(GlobalConstant.SELL_TRADE_CONFIRM_AFFIRMSHARE_TITLE);

                confirmResultModel.setExpense(confirmModel.getFareSx());
                confirmResultModel.setAffirmShare(confirmModel.getTradeConfirmBalance());
//                List<Lookup> tradeLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
//                boolean flag = CalculateAssetsUtils.isT0Fund(tradeLookups, confirmModel.getFundCode());
//                if (flag) {
//                    // 如果是T0
//                    confirmResultModel.setAffirmShare(confirmModel.getConfirmShares());
//                } else {
//                    confirmResultModel.setAffirmShare(confirmModel.getTradeConfirmBalance());
//                }
                // 判断是否是货币,设置不同提示语
                if (isCurrency){
                    confirmResultModel.setTip(GlobalConstant.SELL_TRADE_CONFIRM_TIP_T0);
                }else {
                    confirmResultModel.setTip(GlobalConstant.SELL_TRADE_CONFIRM_TIP);
                }
                confirmResultModel.setFundBusinCode(confirmModel.getFundBusinCode());
                confirmResultModel.setState(1);
                return confirmResultModel;
            }
            confirmResultModel.setState(0);
            return confirmResultModel;
        }

    }


    /**
     * 获取普通基金分红记录
     *
     * @return
     */
    private List<DividendModel> getNormalDividendApplys(String fundCode, OrganProfile organProfile, String taSerialId, Boolean isOrganBao) {
        log.info("queryApplys - userId=" + organProfile.getUserId());
        DividendApplyResult result = new DividendApplyResult();
        try {
            HsDividendQryDto hsDividendQryDto;
            if (StringUtils.isNotBlank(taSerialId)) {
                hsDividendQryDto = HsDividendQryDto.builder()
                    .client_id(organProfile.getExternalClientId())
                    .sort_direction("1")
                    .qry_beginrownum(1)
                    .reqry_recordsum_flag("1")
                    .ta_serial_id(taSerialId)
                    .request_num(GlobalConstant.MAX_REQUEST_NUM)
                    .build();
            } else {
                hsDividendQryDto = HsDividendQryDto.builder()
                    .client_id(organProfile.getExternalClientId())
                    .sort_direction("1")
                    .qry_beginrownum(1)
                    .reqry_recordsum_flag("1")
                    .request_num(GlobalConstant.MAX_REQUEST_NUM)
                    .build();
            }
            Map<String, Object> map = dividendsQueryService.queryDto(hsDividendQryDto);
            List<Map<String, Object>> list = new ArrayList<>();
            // 查询结果
            HundsunUtils.ConvertToList(map, list, result);
            if (!result.getSuccess()) {
                return null;
            }
            // 银行名称
            List<Lookup> bankLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);

            // populate
            List<DividendModel> dividendModelList = ModelPopulateUtils.populateDividend(list, result);
            List<DividendModel> dividendModels = new ArrayList<>();
            // 把T0基金过滤掉，因为T0基金有专门的页面来显示
            dividendFilterOrganBao(dividendModelList, isOrganBao);
            //过滤组合基金记录
            dividendModelList.forEach(dividendModel -> {
                if (!dividendModel.getTradeAccount().startsWith("ZH")) {
                    dividendModels.add(dividendModel);
                }
            });

            List<String> fundCodeList = new ArrayList<String>();
            for (DividendModel dividendModel : dividendModels) {
                // 设置银行名称
                if (bankLookups != null) {
                    for (Lookup lookup : bankLookups) {
                        if (lookup.getRuleValue().equals(dividendModel.getBangNo())) {
                            dividendModel.setBankName(lookup.getRuleText());
                            break;
                        }
                    }
                }
                // 从聚源获取基金信息
                if (!fundCodeList.contains(dividendModel.getFundCode())) {
                    fundCodeList.add(dividendModel.getFundCode());
                }
            }
            List<FundNetValueResult> fundNetValueList = null;
            try {
                fundNetValueList = fundDetailService.getFundNetValueByBatch(fundCodeList, new Date());
            } catch (Exception ex) {
                ExceptionUtil.logError(log, "queryApplys - Exception:", ex);
                throw new SystemDBException("queryApplys Failure!", ex);
            }
            // 如果没有找到聚源数据，则默认为空数组
            if (fundNetValueList == null) {
                fundNetValueList = new ArrayList<>();
            }
            for (DividendModel dividendModel : dividendModels) {
                // 设置基金信息
                for (FundNetValueResult fundNetValue : fundNetValueList) {
                    if (fundNetValue == null) {
                        continue;
                    }
                    if (fundNetValue.getFundCode().equals(dividendModel.getFundCode())) {
                        dividendModel.setFundName(fundNetValue.getChiNameAbbr());
                        break;
                    }
                }
            }

            if (StringUtils.isNotBlank(fundCode)) {
                List<DividendModel> models = new ArrayList<>();
                dividendModels.forEach(dividendModel -> {
                    if (EqualsUtil.equals(dividendModel.getFundCode(), fundCode)) {
                        models.add(dividendModel);
                    }
                });
                return models;
            }
            return dividendModels;
        } catch (BaseException baseException) {
            throw baseException;
        } catch (Exception exception) {
            ExceptionUtil.logError(log, "queryApplys - Exception:", exception);
            throw new SystemDBException("queryApplys Failure!", exception);
        }
    }

    /**
     * 获取瑞富宝分红记录
     *
     * @return
     */
    private List<DividendModel> getWalletDividendApplys(OrganProfile organProfile, String taSerialId) {
        log.info("queryApplys - userId=" + organProfile.getUserId());
        DividendApplyResult result = new DividendApplyResult();
        try {

            HsDividendQryDto hsDividendQryDto;
            if (StringUtils.isNotBlank(taSerialId)) {
                hsDividendQryDto = HsDividendQryDto.builder()
                    .client_id(organProfile.getExternalClientId())
                    .sort_direction("1")
                    .qry_beginrownum(1)
                    .reqry_recordsum_flag("1")
                    .ta_serial_id(taSerialId)
                    .request_num(GlobalConstant.MAX_REQUEST_NUM)
                    .build();
            } else {
                hsDividendQryDto = HsDividendQryDto.builder()
                    .client_id(organProfile.getExternalClientId())
                    .sort_direction("1")
                    .qry_beginrownum(1)
                    .reqry_recordsum_flag("1")
                    .request_num(GlobalConstant.MAX_REQUEST_NUM)
                    .build();
            }
            Map<String, Object> map = dividendsQueryService.queryDto(hsDividendQryDto);
            List<Map<String, Object>> list = new ArrayList<>();
            // 查询结果
            HundsunUtils.ConvertToList(map, list, result);
            if (!result.getSuccess()) {
                return null;
            }
            // 银行名称
            List<Lookup> bankLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);

            // populate
            List<DividendModel> dividendModelList = ModelPopulateUtils.populateDividend(list, result);
            List<DividendModel> dividendModels = new ArrayList<>();
            // 把T0基金过滤掉，因为T0基金有专门的页面来显示
            applyRecordService.filterFund(dividendModelList, true);
            //过滤组合基金记录
            dividendModelList.forEach(dividendModel -> {
                if (!dividendModel.getTradeAccount().startsWith("ZH")) {
                    dividendModels.add(dividendModel);
                }
            });

            List<String> fundCodeList = new ArrayList<String>();
            for (DividendModel dividendModel : dividendModels) {
                // 设置银行名称
                if (bankLookups != null) {
                    for (Lookup lookup : bankLookups) {
                        if (lookup.getRuleValue().equals(dividendModel.getBangNo())) {
                            dividendModel.setBankName(lookup.getRuleText());
                            break;
                        }
                    }
                }
                // 从聚源获取基金信息
                if (!fundCodeList.contains(dividendModel.getFundCode())) {
                    fundCodeList.add(dividendModel.getFundCode());
                }
            }
            List<FundNetValueResult> fundNetValueList = null;
            try {
                fundNetValueList = fundDetailService.getFundNetValueByBatch(fundCodeList, new Date());
            } catch (Exception ex) {
                ExceptionUtil.logError(log, "queryApplys - Exception:", ex);
                throw new SystemDBException("queryApplys Failure!", ex);
            }
            // 如果没有找到聚源数据，则默认为空数组
            if (fundNetValueList == null) {
                fundNetValueList = new ArrayList<>();
            }
            for (DividendModel dividendModel : dividendModels) {
                // 设置基金信息
                for (FundNetValueResult fundNetValue : fundNetValueList) {
                    if (fundNetValue == null) {
                        continue;
                    }
                    if (fundNetValue.getFundCode().equals(dividendModel.getFundCode())) {
                        dividendModel.setFundName(fundNetValue.getChiNameAbbr());
                        break;
                    }
                }
            }
            return dividendModels;
        } catch (BaseException baseException) {
            throw baseException;
        } catch (Exception exception) {
            ExceptionUtil.logError(log, "queryApplys - Exception:", exception);
            throw new SystemDBException("queryApplys Failure!", exception);
        }
    }

    /**
     * 企业宝 过滤
     *
     * @param applys
     */
    @Override
    public void normalFilterOrganBao(List<ApplyModel> applys, boolean isOrganBao) {
        //获取 企业宝 基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
        if (isOrganBao) {
            Iterator<ApplyModel> iterator = applys.iterator();
            while (iterator.hasNext()) {
                ApplyModel model = iterator.next();
                if (!ModelPopulateUtils.isT0Fund(lookups, model.getFundCode())) {
                    iterator.remove();
                }
            }
        }else {
            Iterator<ApplyModel> iterator = applys.iterator();
            while (iterator.hasNext()) {
                ApplyModel model = iterator.next();
                if (ModelPopulateUtils.isT0Fund(lookups, model.getFundCode())) {
                    iterator.remove();
                }
            }
        }
    }

    /**
     * 分红过滤企业基金
     *
     * @param dividendModels
     */
    @Override
    public void dividendFilterOrganBao(List<DividendModel> dividendModels, boolean isOrganBao) {
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
        if (isOrganBao) {
            Iterator<DividendModel> iterator = dividendModels.iterator();
            while (iterator.hasNext()) {
                DividendModel model = iterator.next();
                if (!ModelPopulateUtils.isT0Fund(lookups, model.getFundCode())) {
                    iterator.remove();
                }
            }
        }else {
            Iterator<DividendModel> iterator = dividendModels.iterator();
            while (iterator.hasNext()) {
                DividendModel model = iterator.next();
                if (ModelPopulateUtils.isT0Fund(lookups, model.getFundCode())) {
                    iterator.remove();
                }
            }
        }
    }


}
